package ru.paswd.marketprice.ui.presenter

import moxy.InjectViewState
import ru.paswd.marketprice.Application
import ru.paswd.marketprice.data.repositories.ReceiptsRepository
import ru.paswd.marketprice.ui.view.ReceiptScanView
import ru.paswd.marketprice.utils.StringUtils
import java.lang.RuntimeException

@InjectViewState
class ReceiptScanPresenter : BasePresenter<ReceiptScanView>() {

    companion object {
        const val RECEIPT_TIME = "t"
        const val RECEIPT_SUM = "s"
        const val RECEIPT_FISCAL_NUMBER = "fn"
        const val RECEIPT_FISCAL_DOCUMENT_NUMBER = "i"
        const val RECEIPT_FISCAL_SIGN = "fp"
        const val RECEIPT_TYPE = "n";

        val receiptParams = listOf(
                RECEIPT_TIME,
                RECEIPT_SUM,
                RECEIPT_FISCAL_NUMBER,
                RECEIPT_FISCAL_DOCUMENT_NUMBER,
                RECEIPT_FISCAL_SIGN,
                RECEIPT_TYPE
        )
    }

    fun qrCodeScannedSuccess(params: String) {
        viewState?.stopScanning()
        viewState?.showProgressBar()

        try {
            val map = StringUtils.decodeParams(params)
            checkMap(map)

            ReceiptsRepository.save(
                    Application.instance!!.applicationContext!!,
                    map[RECEIPT_TIME]!!,
                    map[RECEIPT_SUM]!!,
                    map[RECEIPT_FISCAL_NUMBER]!!,
                    map[RECEIPT_FISCAL_DOCUMENT_NUMBER]!!,
                    map[RECEIPT_FISCAL_SIGN]!!,
                    map[RECEIPT_TYPE]!!.toInt()
            ) { success, _ ->
                if (success) {
                    showSuccess()
                } else {
                    showError()
                }
            }
        } catch (_: RuntimeException) {
            showError()
            return
        }
    }

    fun qrCodeScannedWithError(message: String?) {
        viewState?.stopScanning()
        showError()
    }

    fun onBackPressed() {
        viewState?.closeView()
    }

    private fun showSuccess() {
        viewState?.setResultSuccess()
        viewState?.onRefreshed()
    }

    private fun showError() {
        viewState?.setResultFailed()
        viewState?.onRefreshed()
    }

    private fun checkMap(map: Map<String, String>) {
        for (p in receiptParams) {
            if (map[p] == null) {
                throw RuntimeException()
            }
        }

        //Проверка на Int - иначе NumberFormatException
        map[RECEIPT_TYPE]!!.toInt()
    }
}